/**
 * @description 插入表情
 * @author aaron
 */
import Editor from 'wangeditor' // npm 安装

const {$, BtnMenu} = Editor;

import FileUpload from '../../../utils/file-upload';
import createUploadConf from './create-upload-conf';
import {insertImgFn} from "../../../utils/richText";

// import bindEvent from './bind-event/index'

class UploadImage extends BtnMenu {
    constructor(editor) {
        const $elem = $(`<div class="w-e-menu tl-rich-text-menu">
                <i class="tl-icon-upload-img"/>
            </div>`)
        if (!editor.config.customUploadImg) {
            editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
                if (!this.fileUpload) await this.createFileUpload();
                const fileIDs = []
                for (let file of resultFiles) {
                    const fileID = this.fileUpload.addFile({
                        name: file.name,
                        type: file.type,
                        data: file
                    });
                    fileID && fileIDs.push(fileID)
                }
                this.insertImgFn = insertImgFn
            }
        }
        // editor.txt.eventHooks.pasteEvents.push(function (e) {
        //     console.log(e);
        //     debugger
        // })
        // 富文本销毁是销毁
        editor.beforeDestroy(() => this.destroy())
        if (!Array.isArray(editor.txt.eventHooks.clearContentEvents))
            editor.txt.eventHooks.clearContentEvents = []
        editor.txt.eventHooks.clearContentEvents.push(() => this.destroy())
        super($elem, editor)
    }

    /**
     * 创建 panel
     */
    createFileUpload(events) {
        const editor = this.editor;
        if (this.fileUpload) this.destroy();
        const conf = createUploadConf(this.editor);
        let customUploadMonitor = editor.config.customUploadMonitor || {};
        // 是否图片与文本分离
        const customUploadImgSeparate = typeof editor.config.customUploadImgSeparate === "boolean" ?
            editor.config.customUploadImgSeparate : false;
        const outer_complete = customUploadMonitor.complete;
        const fileUpload = this.fileUpload = new FileUpload(this, {
            ...conf,
            events: {
                ...customUploadMonitor,
                complete: (result) => {
                    typeof outer_complete === "function" && outer_complete(result);
                    // 是否将图片追加进入html(富文本中)
                    if (!customUploadImgSeparate) {
                        let flag = true,
                            successLen = result.successful.length,
                            failedLen = result.failed.length;
                        if (successLen > 0) {
                            for (let value of result.successful) {
                                const result = value.response.body || {};
                                if (result.code === 0) {
                                    insertImgFn(editor, {
                                        url: result.data.url,
                                        type: result.data.content_type,
                                        name: result.data.original_name,
                                    })
                                    fileUpload.removeFile(value.id)
                                } else {
                                    failedLen++;
                                }
                            }
                        }
                    }
                }
            }
        })
    }

    /**
     * 菜单表情点击事件
     */
    clickHandler() {
        // 做任何你想做的事情
        // 可参考【常用 API】文档，来操作编辑器
        console.log(this);
        if (!this.fileUpload) this.createFileUpload();
        this.fileUpload.click();
    }

    // 菜单是否被激活（如果不需要，这个函数可以空着）
    // 1. 激活是什么？光标放在一段加粗、下划线的文本时，菜单栏里的 B 和 U 被激活，如下图
    // 2. 什么时候执行这个函数？每次编辑器区域的选区变化（如鼠标操作、键盘操作等），都会触发各个菜单的 tryChangeActive 函数，重新计算菜单的激活状态
    tryChangeActive() {
        // 激活菜单
        // 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
        // 2. this.this.isActive === true
        // this.active()
        // // 取消激活菜单
        // // 1. 菜单 DOM 节点会删掉 .w-e-active
        // // 2. this.this.isActive === false
        // this.unActive()
    }

    destroy() {
        this.fileUpload && this.fileUpload.destroy()
        this.fileUpload = null;
    }
}

export default UploadImage
